<template>
  <div class="container">
    <div class="header">
      <div class="user_info">
        <div class="user_info_photo">
          <img
            v-if="userInfo.wechatPortrait"
            :src="userInfo.wechatPortrait"
            alt
          />
        </div>
        <div class="user_info_other">
          <div class="user_info_other_name">{{ userInfo.wechatNickname }}</div>
          <div class="user_info_other_phone">{{ userInfo.mobile }}</div>
        </div>
      </div>
      <div class="identity">
        <div class="autonym" v-if="userInfo.realStatus === 0">已实名</div>
        <div class="manager">{{ identity }}</div>
      </div>
      <div class="account">
        <!-- <div class="total">
          累计收入:¥ {{ formatMoney(incomes.totalAmount || 0, 2) }}
        </div> -->
        <div class="detail">
          <div class="canextr">
            <div class="money">
              ¥ {{ formatMoney(statistics.balance || 0, 2) }}
            </div>
            <div class="name">可提金额</div>
          </div>
          <div class="extring">
            <div class="money">
              ¥ {{ formatMoney(incomes.withdrawingAmount || 0, 2) }}
            </div>
            <div class="name">提现中</div>
          </div>
          <div class="freeze">
            <div class="money">
              ¥ {{ formatMoney(statistics.frozenAmount || 0, 2) }}
            </div>
            <div class="name">冻结金额</div>
          </div>
        </div>
        <div class="creditScore">
          卖家信用分：{{ userInfo.score }}
          <van-icon
            name="question-o"
            class="creditScore-tips"
            @click="showCreditScoreTips = true"
          />
        </div>
        <!-- <div class="extrBtn" @click="clickWithdraw">提现</div> -->
      </div>
    </div>
    <div class="operate">
      <van-cell title-class="title" title="资金流水" is-link to="/fundflow" />
      <van-cell
        title-class="title"
        title="登录密码"
        @click="showEditPassword = true"
        is-link
      />
      <van-cell
        title-class="title"
        title="提现密码"
        :value="userInfo.hasPayPass === 1 ? '已设定' : '尚未设置提现密码'"
        is-link
        @click="showWithDrawClick"
      />
      <van-cell
        title-class="title"
        title="微信绑定"
        :to="userInfo.hasBindWechat == 0 ? 'authorization' : 'wxrelieve'"
        :value="userInfo.hasBindWechat == 0 ? '去绑定' : '去解绑'"
        is-link
      />
      <van-cell
        title-class="title"
        title="实名认证"
        :value="userInfo.realStatus === 0 ? '已实名' : '进行实名认证'"
        is-link
        @click="showRealName = userInfo.realStatus !== 0"
      />
    </div>
    <div class="loginOut" @click="loginOut">退出登录</div>
    <van-overlay :show="showEditPassword">
      <div class="wrapper">
        <div class="editPassword">
          <div class="title">修改登录密码</div>
          <div class="tips">获取短信验证码，并设置新的登录密码</div>
          <van-form
            :validate-first="true"
            :show-error-message="false"
            ref="passwordForm"
            @submit="onSubmit"
            @failed="onFailed"
          >
            <div class="passwordForm">
              <van-field
                v-model="mobile"
                name="mobile"
                maxlength="11"
                label="当前手机号："
                placeholder="请输入手机号"
                :rules="[
                  { required: true, message: '请填写手机号' },
                  {
                    pattern: /^1[3456789]\d{9}$/,
                    message: '请填写正确手机号码',
                  },
                ]"
              />
              <van-field
                name="code"
                v-model="code"
                center
                maxlength="6"
                label="验证码："
                placeholder="请输入短信验证码"
                :rules="[{ required: true, message: '请填写短信验证码' }]"
              >
                <template #button>
                  <div class="sendCode" @click="sendSms" v-if="!hasSendCode">
                    获取验证码
                  </div>
                  <div class="sendCode" v-else>{{ second }}s</div>
                </template>
              </van-field>
              <van-field
                v-model="newPassword"
                name="newPassword"
                :type="passwordType"
                label="密码："
                placeholder="6-20位含数字/英文/符号"
                :rules="[
                  { required: true, message: '请填写新密码' },
                  {
                    pattern: /^[a-zA-Z]\w{5,19}$/,
                    message:
                      '以字母开头，长度在6~20之间，只能包含字母、数字和下划线',
                  },
                ]"
              >
                <template slot="right-icon">
                  <van-icon
                    class="showIcon"
                    :name="passwordType == 'text' ? 'closed-eye' : 'eye-o'"
                    @click="switchPasswordType"
                  />
                </template>
              </van-field>
            </div>
            <div class="operateBtn">
              <van-button class="btn submit" native-type="submit">
                提交
              </van-button>
              <div class="btn close" @click="closeEditPassword">关闭</div>
            </div>
          </van-form>
          <div class="closeIcon" @click="closeEditPassword"></div>
        </div>
      </div>
    </van-overlay>
    <van-overlay :show="showWithDraw">
      <div class="wrapper">
        <div :class="'editWithDraw ' + (step == 2 ? 'step2' : '')">
          <div class="title">设置提现密码</div>
          <div class="step">
            <img v-if="step === 1" src="./images/step1.png" />
            <img v-else src="./images/step2.png" />
          </div>
          <div class="tips">完成身份信息验证，修改提现方式</div>
          <div class="passwordForm">
            <van-field
              v-if="step === 2"
              :type="passwordType"
              v-model="withDrawPw"
              :maxlength="12"
              label="提现密码："
              placeholder="请设置6-12位纯数字"
              bind:click-icon="switchPasswordType"
            >
              <template slot="right-icon">
                <van-icon
                  class="showIcon"
                  :name="passwordType == 'text' ? 'closed-eye' : 'eye-o'"
                  @click="switchPasswordType"
                />
              </template>
            </van-field>
            <van-field
              v-if="step === 1"
              v-model="idCard"
              label="身份证号："
              placeholder="请输入身份证号"
            />
            <van-field
              v-if="step === 1"
              v-model="userName"
              label="真实姓名："
              placeholder="请输入真实姓名"
            />
          </div>
          <div class="operateBtn">
            <van-button class="btn submit" @click="onWithDrawSubmit">
              {{ step === 1 ? '下一步' : '提交' }}
            </van-button>
            <div class="btn close" @click="closeEditWithDraw">关闭</div>
          </div>
          <div class="closeIcon" @click="closeEditWithDraw"></div>
        </div>
      </div>
    </van-overlay>
    <van-overlay :show="showRealName">
      <div class="wrapper">
        <div class="editRealName">
          <div class="title">实名认证</div>
          <div class="tips">完成身份信息验证，修改提现方式</div>
          <div class="passwordForm">
            <van-form
              ref="RealName"
              @submit="onRealNameSubmit"
              @failed="onFailed"
              :show-error-message="false"
              :validate-first="true"
            >
              <van-field
                label="身份证号："
                v-model="idCard"
                name="idCard"
                placeholder="请输入身份证号"
                :rules="[{ required: true, message: '请填写身份证号' }]"
              />
              <van-field
                label="真实姓名："
                name="userName"
                v-model="userName"
                placeholder="请输入真实姓名"
                :rules="[{ required: true, message: '请填写真实姓名' }]"
              />
              <div class="operateBtn">
                <van-button class="btn submit" native-type="submit">
                  提交
                </van-button>
                <div class="btn close" @click="closeEditRealName">关闭</div>
              </div>
            </van-form>
          </div>
          <div class="closeIcon" @click="closeEditRealName"></div>
        </div>
      </div>
    </van-overlay>
    <van-overlay :show="showCreditScoreTips">
      <div class="wrapper" @click.stop>
        <div class="creditScoreTips">
          <div class="title">卖家信用分</div>
          <div class="tips-content">
            <div>
              卖家信用分将会对您余额提现速度，商品发布数量等产生影响，您可以通过以下方式获得更高的信用分。
            </div>
            <br />
            <div>1.完成实名认证</div>
            <div>2.寄售商品且未发生售后问题</div>
            <div>3.完成微信绑定等</div>
          </div>
          <!-- <div class="sendBtn" @click="closeCreditScoreTips">确认</div> -->
          <div class="closeIcon" @click="closeCreditScoreTips"></div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import { Toast, Dialog } from 'vant'
import { checkUserIdentity_post } from '@/otherApi/index'
import {
  getUserInfo_get,
  saveUserWithdrawPassword_post,
  authenticateRealName_post,
  query_statistics_get,
  query_sum_incomes_post,
} from '@/api/app/seller'
import {
  forgetSendMobileCode_post,
  forgetCheckMobileCode_post,
  logout_post,
} from '@/api/app/seller/login'
import { formatMoney } from '../../util/index'
import md5 from 'md5'
export default {
  name: 'myCenter',
  data () {
    this.phonePattern = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/
    this.passwordPattern = /^(?!bai[0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/
    this.withDrawPattern = /^\d{6,12}$/
    return {
      showEditPassword: false,
      mobile: '',
      code: '',
      newPassword: '',
      hasSendCode: false,
      second: 60,
      timer: null,
      showWithDraw: false,
      passwordType: 'password',
      withDrawPw: '',
      idCard: '',
      userName: '',
      step: 1,
      showRealName: false,
      userInfo: {},
      incomes: {},
      statistics: {},
      token: '',
      showCreditScoreTips: false,
      creditInfo: ''
    }
  },
  created () {
    this.getUserInfo()
    query_sum_incomes_post().then((data) => {
      console.log(data)
      this.incomes = data
    })
    query_statistics_get().then((data) => {
      this.statistics = data
    })
  },
  computed: {
    identity () {
      const sellerType = {
        0: '个人商家',
        1: '品质商家',
        2: '管理员',
      }
      return sellerType[this.userInfo.sellerType]
    },
  },
  methods: {
    loginOut () {
      Dialog.confirm({
        title: '提示',
        message: '确认退出？',
      })
        .then(() => {
          logout_post().then((data) => {
            this.$notify({
              message: '退出成功！',
              type: 'success',
              onClose: () => {
                this.$router.push('/login')
              },
            })
          })
        })
        .catch(() => {
          // on cancel
        })
    },
    clickWithdraw () {
      if (this.userInfo.realStatus !== 0) {
        this.showRealName = true
      } else if (this.userInfo.hasPayPass !== 1) {
        this.showWithDraw = true
      } else {
        this.$router.push('/withdraw')
      }
    },
    showWithDrawClick () {
      if (this.userInfo.realStatus !== 0) {
        this.showRealName = true
      } else if (this.userInfo.hasPayPass !== 1) {
        this.showWithDraw = true
      }
    },
    getUserInfo () {
      getUserInfo_get().then((data) => {
        this.userInfo = data
      })
    },
    formatMoney,
    onRealNameSubmit (values) {
      authenticateRealName_post({
        data: values,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      }).then((data) => {
        this.$notify({
          message: '实名认证成功！',
          type: 'success',
          onClose: () => {
            location.reload()
          },
        })
      })
    },
    onWithDrawSubmit () {
      if (this.step === 1) {
        if (!this.idCard) {
          return this.$toast('请输入身份证')
        }
        if (!this.userName) {
          return this.$toast('请输入真实姓名')
        }
        checkUserIdentity_post(
          {
            data: {
              idCard: this.idCard,
              userName: this.userName,
            },
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          },
          'pay_pass'
        ).then((data) => {
          this.step = 2
          this.token = data
        })
      } else {
        if (!this.withDrawPattern.test(this.withDrawPw)) {
          return this.$toast('请输入6-12位纯数字密码')
        }
        saveUserWithdrawPassword_post({
          data: {
            newPassword: md5(this.withDrawPw),
            token: this.token,
          },
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        }).then(() => {
          this.closeEditWithDraw()
          this.$notify({
            message: '提现密码设置成功',
            type: 'success',
            onClose: () => {
              location.reload()
            },
          })
        })
      }
    },
    onFailed (values) {
      if (Array.isArray(values.errors)) {
        Toast.fail(values.errors[0].message)
      }
    },
    onSubmit (values) {
      forgetCheckMobileCode_post({
        data: { ...values },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      }).then(() => {
        this.closeEditPassword()
        this.$notify({
          message: '修改密码成功！',
          type: 'success',
          onClose: () => {
            location.reload()
          },
        })
      })
    },
    switchPasswordType () {
      this.passwordType =
        this.passwordType === 'password' ? 'text' : 'password'
    },
    closeEditRealName () {
      this.idCard = ''
      this.userName = ''
      this.showRealName = false
    },
    closeEditWithDraw () {
      this.showWithDraw = false
      this.idCard = ''
      this.userName = ''
      this.step = 1
      this.withDrawPw = ''
      this.passwordType = 'password'
    },
    closeEditPassword () {
      this.showEditPassword = false
      this.timer = null
      this.second = 60
      this.hasSendCode = false
      this.newPassword = ''
      this.code = ''
      this.mobile = ''
      this.passwordType = 'password'
    },
    sendSms () {
      if (this.hasSendCode) {
        return
      }
      this.$refs.passwordForm
        .validate('mobile')
        .then(() => {
          forgetSendMobileCode_post({
            data: {
              mobile: this.mobile,
              challenge: '111111',
            },
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          }).then(() => {
            this.hasSendCode = true
            this.$toast('短信验证码发送成功，请注意查收！')
            this.timer = setInterval(() => {
              console.log(this.second)
              this.second--
              if (this.second === 0) {
                this.hasSendCode = false
                clearInterval(this.timer)
                this.timer = null
                this.second = 60
              }
            }, 1000)
          })
        })
        .catch((err) => {
          Toast.fail(err.message)
        })
    },
    closeCreditScoreTips () {
      this.showCreditScoreTips = false
    },
    // showCreditScoreTips () {
    //   this.showCreditScoreTips = false
    // }
  },
}
</script>
<style lang="scss" scoped src="./styles/index.scss"></style>
